// import 'package:appsflyer_sdk/appsflyer_sdk.dart';
// import 'package:euromillions/tools/EJ_config.dart';
import 'package:flutter/material.dart';

import 'package:webview_flutter/webview_flutter.dart';
// #docregion platform_imports
// Import for Android features.
import 'package:webview_flutter_android/webview_flutter_android.dart';
// Import for iOS features.
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';

import '../tools/KaL_Config.dart';

class EJWebViewPage extends StatefulWidget {
  const EJWebViewPage({
    Key? key,
    required this.url,
    required this.title,
    this.haveAppBar = true,
  }) : super(key: key);

// const Browser(Key key, this.url, this.title) : super(key: key);

  final String url;
  final String title;
  final bool haveAppBar;

  @override
  State<EJWebViewPage> createState() => _EJWebViewPageState();
}

class _EJWebViewPageState extends State<EJWebViewPage>
    with WidgetsBindingObserver {
  // final GlobalKey webViewKey = GlobalKey();

  //js充值回传参数
  var PS_backParameter = {};
  //跳转外部地址
  late Uri PS_outsideUrl = Uri.parse('');
  //拉起第三方app状态:0=无拉起
  int PS_openThirdStatus = 0;

  late bool PS_pageLoaded;

  String PS_af_deeplink = '';
  String PS_af_firstTime_deeplink = '';
  String PS_onInstallData = '';

  late final WebViewController PS_webController;
  late final WebViewCookieManager PS_webViewCookieManagerer;

  String PS_channelid = KaL_Config.KaL_channelid;
  String PS_packageName = KaL_Config.KaL_packageName;
  String PS_channelName = KaL_Config.KaL_channelName;

  //初始化analytics
  // static FirebaseAnalytics PS_analytics = FirebaseAnalytics.instance;
  // static FirebaseAnalyticsObserver PS_observer =
  //     FirebaseAnalyticsObserver(analytics: PS_analytics);

  // //facebook
  // static final PS_facebookAppEvents = FacebookAppEvents();

  // //af
  // late AppsflyerSdk PS_appsflyerSdk;

  ///webview控制器
  // late WebViewController _controller;

  // final Completer<WebViewController> _controller =
  //     Completer<WebViewController>();
  // late WebViewController _webControl;
  late double PS_progress = 0.01; //H5加载进度值
  final double PS_VISIBLE = 1;
  final double PS_GONE = 0;
  late double PS_progressHeight = PS_GONE; //H5加载进度条高度

  //显示或隐藏进度条
  void PS_setProgressVisible(double isVisible) {
    setState(() {
      PS_progressHeight = isVisible;
    });
  }

  ///appflyer事件上报
  // void PS_setAFAppflyerEvent(JavaScriptMessage message) {
  //   var afSDK = PS_Tool_Appflyer.instance.appsflyerSdk;
  //   String jsonStr = message.message;
  //   PS_FirebaseTool.PS_appflyerAnalyticsEventWith(
  //     context,
  //     PS_webController,
  //     jsonStr,
  //     afSDK,
  //   );
  // }

  //facebook事件上报
  // void PS_setFacebookEvent(JavaScriptMessage message) {
  //   String jsonStr = message.message;
  //   PS_FirebaseTool.PS_faceBookAnalyticsEventWith(
  //     context,
  //     PS_webController,
  //     jsonStr,
  //     PS_facebookAppEvents,
  //   );
  // }

  //firebase事件上报
  // void PS_setFirebaseEvent(JavaScriptMessage message) {
  //   String jsonStr = message.message;
  //   PS_FirebaseTool.PS_firebaseAnalyticsEventWith(
  //     context,
  //     PS_webController,
  //     jsonStr,
  //     analytics: PS_analytics,
  //   );
  // }

  // void PS_webviewMessageReceived(JavaScriptMessage message) {
  //   String jsonStr = message.message;
  //   Map dataMap = jsonDecode(jsonStr);
  //   PS_backParameter = dataMap;
  //   if (dataMap.isEmpty) {
  //     return;
  //   }
  //   String methodName = dataMap['method'];
  //   if (methodName == "launchURL") {
  //     //拉起第三方app
  //     String url = dataMap['data']['url'];
  //     String pkgStr = dataMap['data']['pkg'];
  //     // BotToast.showText(text: url);
  //     PS_outsideUrl = Uri.parse(url);
  //     PS_launchUrl(PS_outsideUrl, pkgStr);
  //   } else {
  //     switch (methodName) {
  //       case 'logFirebaseEvent':
  //         PS_setFirebaseEvent(message);
  //         break;
  //       case 'logFacebookEvent':
  //         PS_setFacebookEvent(message);
  //         break;
  //       case 'logAppsflyerEvent':
  //         PS_setAFAppflyerEvent(message);
  //         break;
  //       default:
  //     }
  //   }
  // }

  // ignore: non_constant_identifier_names
  // Future<void> PS_launchUrl(Uri Url, String appPkg) async {
  //   debugPrint("-----can open? $Url");

  //   if (!await launchUrl(Url, mode: LaunchMode.externalApplication)) {
  //     // throw Exception('Could not launch $Url');
  //     debugPrint("can not open $Url");
  //     PS_openThirdStatus = -100;
  //     //fail
  //     PS_payingCallBack(-100);

  //     BotToast.showSimpleNotification(
  //         title:
  //             'Can not open this third-party App, kindly ensure you have installed it.');
  //   }
  //   debugPrint("----- open $Url");
  //   PS_openThirdStatus = 100;
  //   //success
  //   PS_payingCallBack(100);
  //   PS_launchThirdEvent(PS_analytics, "launchURL", appPkg);
  // }

  // void PS_launchThirdEvent(
  //     FirebaseAnalytics analytics, String methodName, String pkg) async {
  //   // PS_FirebaseTool._sendAnalyticsEvent(name, parame, analytics!);
  //   var data = {"packageName": pkg};
  //   await analytics.logEvent(name: methodName, parameters: data);
  // }

  //js事件callback
  // void PS_payingCallBack(int states) async {
  //   if (PS_backParameter.isEmpty) {
  //     PS_openThirdStatus = 0;
  //     return;
  //   }

  //   if (PS_openThirdStatus != 100 && PS_openThirdStatus != -100) {
  //     return;
  //   }

  //   String callBackName = PS_backParameter['callback'];

  //   /*
  //   跳出失败：-100
  //   跳出成功：100
  //   支付完成返回来：200
  //   */
  //   Map callbackParame = {"status": states};
  //   String paramJson = json.encode(callbackParame);
  //   await PS_webController.runJavaScript("$callBackName($paramJson)");
  //   debugPrint("runJavaScript---$callBackName($paramJson)");
  //   if (states == -100 || states == 200) {
  //     //callback完恢复初始状态
  //     PS_openThirdStatus = 0;
  //   }
  // }

  //进入app需要webview给js传递deeplink参数
  // void PS_loadedAppCallback() async {
  //   // PS_af_firstTime_deeplink =
  //   //     PS_Tool_Appflyer.instance.PS_AF_firstTime_deeplink ?? "";
  //   // PS_af_deeplink = PS_Tool_Appflyer.instance.PS_AF_deep_link ?? "";
  //   PS_onInstallData = PS_Tool_Appflyer.instance.PS_AF_onInstallData ?? "";
  //   if (PS_Tool_Appflyer.instance.PS_AF_DLStatus == "LINK FOUND") {
  //     debugPrint(
  //         "runJavaScript---appDidBecomeActive-------------------LINK FOUND");
  //     PS_af_firstTime_deeplink =
  //         PS_Tool_Appflyer.instance.PS_AF_firstTime_deeplink ?? "";
  //     PS_af_deeplink = PS_Tool_Appflyer.instance.PS_AF_DLStatus ?? "";
  //   } else {
  //     debugPrint(
  //         "runJavaScript---appDidBecomeActive-------------------LINK NOT FOUND");
  //     PS_af_deeplink = "";
  //   }
  //   Map<String, dynamic> callbackParame = {
  //     "af_first_time_deep_link": PS_af_firstTime_deeplink,
  //     "af_conversion_data": PS_onInstallData,
  //     "af_deep_link": PS_af_deeplink
  //   };
  //   String paramJson = json.encode(callbackParame);
  //   PS_webController.runJavaScript("appDidBecomeActive($paramJson)");
  //   debugPrint("runJavaScript---appDidBecomeActive($paramJson)");
  // }

  //webview初始化
  void PS_initWebview() async {
    String PS_UAString =
        // 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 Google-Apps-Script';
        "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 SQRGroup/PlayScore/1.0.0/$PS_channelid($PS_packageName)";

    /*
    CookieManager初始化
    */
    PlatformWebViewCookieManagerCreationParams PS_CookieManagerCreationParams =
        const PlatformWebViewCookieManagerCreationParams();

    //从特定的平台实现构建
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      PS_CookieManagerCreationParams = WebKitWebViewCookieManagerCreationParams
          .fromPlatformWebViewCookieManagerCreationParams(
        PS_CookieManagerCreationParams,
      );
    } else if (WebViewPlatform.instance is AndroidWebViewPlatform) {
      PS_CookieManagerCreationParams = AndroidWebViewCookieManagerCreationParams
          .fromPlatformWebViewCookieManagerCreationParams(
        PS_CookieManagerCreationParams,
      );
    }

    //创建manager对象
    final WebViewCookieManager PS_webViewCookieManager =
        WebViewCookieManager.fromPlatformCreationParams(
      PS_CookieManagerCreationParams,
    );
    PS_webViewCookieManagerer = PS_webViewCookieManager;

    //从特定平台的创建参数构建
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      final WebKitWebViewCookieManager webKitManager =
          PS_webViewCookieManager.platform as WebKitWebViewCookieManager;
    } else if (WebViewPlatform.instance is AndroidWebViewPlatform) {
      final AndroidWebViewCookieManager androidManager =
          PS_webViewCookieManager.platform as AndroidWebViewCookieManager;
    }

    // #docregion platform_features
    late final PlatformWebViewControllerCreationParams PS_params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      PS_params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      PS_params = const PlatformWebViewControllerCreationParams();
    }

    final WebViewController PS_WebController =
        WebViewController.fromPlatformCreationParams(PS_params);

    //配置webController
    PS_WebController
      // ..runJavaScript(PS_UAString)
      ..loadRequest(Uri.parse(widget.url))
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..addJavaScriptChannel(
        PS_channelName,
        onMessageReceived: (JavaScriptMessage message) {
          debugPrint('++++++onMessageReceived');
          // PS_webviewMessageReceived(message);
        },
      )
      ..setNavigationDelegate(NavigationDelegate(
        onProgress: (int PS_progress) {
          //progress值为0-100
          this.PS_progress = PS_progress.toDouble() / 100.0; //计算成0.0-1.0之间的值
          // debugPrint('WebView is loading (PS_progress : $PS_progress%)');
        },
        onPageStarted: (String url) {
          //H5页面开始加载时触发
          PS_setProgressVisible(PS_VISIBLE); //显示加载进度条
          // debugPrint('Page started loading: $url');
        },
        onPageFinished: (String url) {
          PS_setProgressVisible(PS_GONE); //隐藏加载进度条
          // debugPrint('Page finished loading: $url');
          if (!PS_pageLoaded) {
            //页面加载完,callback deeplink一次
            // PS_loadedAppCallback();
            debugPrint('Page finished loading: $url');
            PS_pageLoaded = true;
          }
        },
        onWebResourceError: (WebResourceError error) {
          debugPrint('''
              Page resource error:
              code: ${error.errorCode}
              description: ${error.description}
              errorType: ${error.errorType}
              isForMainFrame: ${error.isForMainFrame}
          ''');
        },
        onNavigationRequest: (NavigationRequest request) {
          if (request.url.startsWith('http://') ||
              request.url.startsWith('https://')) {
            return NavigationDecision.navigate;
          } else {
            //拦截，并拉起第三方
            // PS_launchUrl(Uri.parse(request.url), "");

            return NavigationDecision.prevent;
          }
        },
      ));

    // #docregion platform_features
    if (PS_WebController.platform is AndroidWebViewController) {
      AndroidWebViewController.enableDebugging(true);
      (PS_WebController.platform as AndroidWebViewController)
          .setMediaPlaybackRequiresUserGesture(false);
    }
    PS_WebController.platform.setUserAgent(PS_UAString);

    // #enddocregion platform_features
    //赋值controller
    PS_webController = PS_WebController;
  }

  // @override
  // void didChangeAppLifecycleState(AppLifecycleState state) {
  //   debugPrint("-didChangeAppLifecycleState-" + state.toString());
  //   switch (state) {
  //     case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。
  //       break;
  //     case AppLifecycleState.resumed: //从后台切换前台，界面可见
  //       debugPrint('web--从后台切换前台');
  //       PS_payingCallBack(200);
  //       PS_loadedAppCallback();
  //       break;
  //     case AppLifecycleState.paused: // 界面不可见，后台
  //       String dlStatus = PS_Tool_Appflyer.instance.PS_AF_DLStatus!;
  //       debugPrint("dlStatus---$dlStatus");
  //       PS_Tool_Appflyer.instance.PS_AF_DLStatus = "AppLifecycleState.paused";

  //       break;
  //     case AppLifecycleState.detached: // APP结束时调用
  //       break;
  //     case AppLifecycleState.hidden:
  //     // TODO: Handle this case.
  //   }
  // }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    //监听app生命状态
    WidgetsBinding.instance.addObserver(this);

    // PS_appsflyerSdk = PS_Tool_Appflyer.instance.appsflyerSdk;
    // PS_af_deeplink = PS_Tool_Appflyer.instance.PS_AF_deep_link ?? '';
    // PS_af_firstTime_deeplink =
    //     PS_Tool_Appflyer.instance.PS_AF_firstTime_deeplink ?? '';
    // PS_onInstallData = PS_Tool_Appflyer.instance.PS_AF_onInstallData ?? '';

    PS_pageLoaded = false;

    // initstallAppFlyer();
    PS_initWebview();
  }

  @override
  Widget build(BuildContext context) {
    WebViewWidget webView = WebViewWidget(
      controller: PS_webController,
    );

    // ignore: deprecated_member_use
    return WillPopScope(
      child: widget.haveAppBar
          ?
          //有AppBar
          Scaffold(
              appBar: AppBar(
                title: Text(widget.title),
                backgroundColor: Colors.white,
                foregroundColor: KaL_Config.KaL_MainColor,
              ),
              body: SafeArea(
                child: Stack(
                  children: [
                    webView,
                    SizedBox(
                        //进度条
                        height: PS_progressHeight,
                        child: LinearProgressIndicator(
                          backgroundColor: Colors.white,
                          valueColor: const AlwaysStoppedAnimation(
                              Color.fromARGB(255, 243, 33, 33)),
                          value: PS_progress, //当前加载进度值
                        )),
                  ],
                ),
              ),
            )
          :
          //无AppBar
          Scaffold(
              backgroundColor: Colors.black,
              body: SafeArea(
                child: Stack(
                  children: [
                    webView,
                    SizedBox(
                        //进度条
                        height: PS_progressHeight,
                        child: LinearProgressIndicator(
                          backgroundColor: Colors.white,
                          valueColor: const AlwaysStoppedAnimation(
                              Color.fromARGB(255, 243, 33, 33)),
                          value: PS_progress, //当前加载进度值
                        )),
                  ],
                ),
              ),
            ),
      onWillPop: () async {
        //拦截页面返回事件
        if (await PS_webController.canGoBack()) {
          PS_webController.goBack(); //返回上个网页
          return false;
        }
        return true; //退出当前页
      },
    );
  }
}
